﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 自旋锁
{
    public class QueueSpinLock<T>
    {
        Queue<T> msgQueue = new Queue<T>(65536);
        bool lockTaken = false;
        SpinLock spin = new SpinLock();

        public int GetQueueCount()
        {
            return msgQueue.Count;
        }

        public void InQueue(T t)
        {
            lockTaken = false;
            try
            {
                spin.Enter(ref lockTaken);
                msgQueue.Enqueue(t);
            }
            finally
            {
                if (lockTaken) spin.Exit(lockTaken);
            }
        }

        public T OutQueue()
        {
            T t = default(T);
            lockTaken = false;
            try
            {
                spin.Enter(ref lockTaken);
                t = msgQueue.Dequeue();
            }
            finally
            {
                if (lockTaken) spin.Exit(lockTaken);
            }
            return t;
        }

    }
}
